<script setup lang="ts">
import {
  getWeixinLoginToken,
  getWeixinLoginUserInfo,
  getWeixinPreData
} from '@/api';
import useBroadcast from '../../composables/useBroadcast';
import { useOAuth } from '../../composables';

const broadcast = useBroadcast();
const oauth = useOAuth();

if (window.location.search) {
  const code = /code=((.*))&state/.exec(window.location.search)![1];
  if (code) {
    broadcast.send(code);

    window.close();
  }
}

const onWXLogin = async () => {
  const { appId, appSecret, redirectUri, scope, state } =
    await getWeixinPreData<{
      appId: string;
      appSecret: string;
      redirectUri: string;
      scope: string;
      state: string;
    }>();

  window.open(
    `https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`,
    '',
    'height=525,width=585,toolbar=no,menubar=no,location=no,status=no,location=yes,resizable=yes'
  );

  // 等待扫码成功
  broadcast.wait().then(async (data: any) => {
    broadcast.clear();

    const { access_token, openid } = await getWeixinLoginToken<{
      access_token: string;
      openid: string;
    }>({
      appId,
      appSecret,
      code: data.code
    });

    const { nickname, headimgurl } = await getWeixinLoginUserInfo<{
      nickname: string;
      headimgurl: string;
    }>({
      access_token,
      openid
    });

    oauth.oauthLogin('WX', { openid, nickname, headimgurl });
  });
};
</script>

<template>
  <div @click="onWXLogin">
    <MSvgIcon name="wexin" class="w-4 cursor-pointer" />
    <div id="wx_login_container" />
  </div>
</template>
